import { createStore } from 'vuex';
import { api, validFeeds } from '@/common/api';

interface IStore {
  items: { [key: string]: any },
  users: { [key: string]: any },
  feeds: { [key: string]: any },
}

const state = () => {
  const s: IStore = {
    items: {},
    users: {},
    feeds: {}
  };
  for (const feed in validFeeds) {
    s.feeds[feed] = {};
  }
  return s;
};

const mutations = {
  SET_FEED: (state: IStore, { feed, ids, page }: any) => {
    state.feeds[feed][page] = ids;
  },
  SET_ITEM: (state: IStore, { item }: any) => {
    if (item) {
      state.items[item.id] = item;
    }
  },
  SET_ITEMS: (state: IStore, { items }: any) => {
    items.forEach((item: any) => (state.items[item.id] = item));
  },
  SET_USER: (state: IStore, { id, user }: any) => {
    state.users[id] = user || false;
  }
};

const actions = {
  async FETCH_FEED({ commit, state }: any, { feed, page }: any) {
    await api.getFeeds(
      feed,
      page,
      (items: any) => {
        const ids = items.map((item: any) => item.id);
        commit('SET_FEED', { feed, ids, page });
        commit('SET_ITEMS', { items });
      },
      (state.feeds[feed][page] || []).map((id: any) => state.items[id])
    );
  },

  async FETCH_ITEM({ commit, state }: any, { id }: any) {
    await api.getItem(
      id,
      (item: any) => commit('SET_ITEM', { item }),
      Object.assign({ id, loading: true, comments: [] }, state.items[id])
    );
  },

  async FETCH_USER({ commit, state }: any, { id }: any) {
    await api.getUser(
      id,
      (user: any) => commit('SET_USER', { id, user }),
      Object.assign({ id, loading: true }, state.users[id])
    );
  }
};

const getters = {
  getItems: (state: IStore) => (feed: any, page: any) => {
    return (state.feeds[feed][page] || []).map((id: any) => state.items[id]);
  }
};
const m: any = module;
if (m.hot) {
  m.hot.accept([actions, mutations], () => {
    // store.hotUpdate({
    //   actions,
    //   mutations,
    // })
  });
}

export function _createStore() {
  return createStore({
    state,
    mutations,
    actions,
    getters
  });
}
